package cn.yh.register.msm.api;

import cn.yh.register.common.result.Result;
import cn.yh.register.msm.service.MsmService;
import cn.yh.register.msm.util.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@Api(tags = "短信服务接口")
@RestController
@RequestMapping("/api/msm")
public class MsmApiController {

    @Autowired
    MsmService msmService;

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    //发送手机验证码
    @ApiOperation("发送验证码")
    @GetMapping("/send/{phone}")
    public Result<?> sendSms(@PathVariable String phone){
        //如果验证码没失效 直接返回ok
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return Result.ok();
        }
        //生成验证码
        code = RandomUtil.getSixBitRandom();
        if (msmService.send(phone, code)) {
            //发送成功  需要保存一段时间  存入redis中 设置有效时间
            redisTemplate.opsForValue().set(phone, code, 1, TimeUnit.MINUTES);
            return Result.ok();
        }
        return Result.fail().message("验证码错误");
    }




}
